//
//  ShippingAddressViewController.m
//  FactorySale
//
//  Created by 主事丫环 on 2020/3/27.
//  Copyright © 2020 主事丫环. All rights reserved.
//

#import "ShippingAddressViewController.h"
#import "ShippingAddressTableViewCell.h"
#import "AddNewAddressViewController.h"// 添加新地址控制器

@interface ShippingAddressViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray *mydateSource;
@property (nonatomic, strong) UIImageView *emptyImageView;

@end

@implementation ShippingAddressViewController

#pragma mark ***页面刷新
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //    [singlTool shareSingTool].isLjiBuy = 2;
    //    if ([singlTool shareSingTool].needReasfh) {
    //        [self.myTableView.mj_header beginRefreshing];
    //        [singlTool shareSingTool].needReasfh = NO;
    //    }
    [self requestData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"收货地址";
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
    //self.view.backgroundColor = Main_BackGroundColor;
    self.view.backgroundColor = [UIColor whiteColor];
    self.mydateSource = [NSMutableArray arrayWithCapacity:1];
    
    [self.view addSubview:self.myTableView];
    
    [self.rightbutton setTitle:@" 添加" forState:(UIControlStateNormal)];
    [self.rightbutton setTitleColor:[UIColor colorWithHexString:@"#1EB491"] forState:(UIControlStateNormal)];
    [self.rightbutton setImage:imgname(@"AddNewAddImg") forState:UIControlStateNormal];
    [self.rightbutton addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.emptyImageView = [[UIImageView alloc] init];
    self.emptyImageView.image = [UIImage imageNamed:@"空空如也"];
    self.emptyImageView.hidden = YES;
    [self.view addSubview:self.emptyImageView];
    [self.emptyImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(147);
        make.left.offset(104);
        make.right.offset(-104);
        make.height.offset(180);
    }];
    
    // Do any additional setup after loading the view.
}

- (void)rightButtonAction:(UIButton *)button {
    NSLog(@"onClickedOKbtn");
    AddNewAddressViewController *vc = [[AddNewAddressViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)requestData {
    kWeakSelf;
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
    
    [weakSelf.mydateSource removeAllObjects];
    [NetWorkTool POST:addList param:param success:^(id dic) {
        NSLog(@"打印一下 收货地址 列表所有数据 %@", dic);
        
        //self.mydateSource = [ShippingAddressListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        self.mydateSource = [SelectAreaModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        
        if (self.mydateSource.count>0) {
            self.emptyImageView.hidden = YES;
        } else {
            self.emptyImageView.hidden = NO;
        }
        [self.myTableView reloadData];
        [self.myTableView.mj_header endRefreshing];
    } other:^(id dic) {
        [weakSelf.mydateSource removeAllObjects];
        [self.myTableView reloadData];
        [self.myTableView.mj_header endRefreshing];
        if (self.mydateSource.count>0) {
            self.emptyImageView.hidden = YES;
        } else {
            self.emptyImageView.hidden = NO;
        }
    } fail:^(NSError *error) {
        [weakSelf.mydateSource removeAllObjects];
        [self.myTableView reloadData];
        [self.myTableView.mj_header endRefreshing];
        if (self.mydateSource.count>0) {
            self.emptyImageView.hidden = YES;
        } else {
            self.emptyImageView.hidden = NO;
        }
    } needUser:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _mydateSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 97;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    //定义Cell标识 每一个Cell对应一个自己的标识
    NSString *CellIdentitier = [NSString stringWithFormat:@"cell%ld%ld",(long)indexPath.section, (long)indexPath.row];
    //通过唯一标识创建Cell实例
    ShippingAddressTableViewCell *mycell = [tableView dequeueReusableCellWithIdentifier:CellIdentitier];
    //判断为空进行初始化  --(当拉动页面显示超过主页面内容的时候就会重用之前的cell,w而不会再次初始化)
    if (!mycell) {
        mycell = [[ShippingAddressTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentitier];
    }
    
    mycell.selectionStyle = UITableViewCellSelectionStyleNone;//取消cell的点击状态
    //ShippingAddressListModel *model = [_mydateSource safeObjectAtIndex:indexPath.row];
    SelectAreaModel *model = [_mydateSource safeObjectAtIndex:indexPath.row];
    
    [mycell refasf:model];
    
    kWeakSelf;
    mycell.editOrDelBlock = ^(NSInteger index) {
        if (index == 0) { //设置默认
            [weakSelf requestData];
        } else if (index == 1) { //编辑
            AddNewAddressViewController *edit = [[AddNewAddressViewController alloc] init];
            edit.model = model;
            [weakSelf.navigationController pushViewController:edit animated:YES];
        }
    };
    return mycell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectAreaModel *model = [_mydateSource safeObjectAtIndex:indexPath.row];
    if (self.addressBlockHandle) {
        self.addressBlockHandle(model);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(UITableView *)myTableView{
    if (!_myTableView) {
        _myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kNaviHeight, KWIDTH, KHEIGHT - kNaviHeight) style:(UITableViewStyleGrouped)];
        _myTableView.backgroundColor = [UIColor clearColor];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        _myTableView.estimatedRowHeight = 90;
        _myTableView.rowHeight = UITableViewAutomaticDimension;
        _myTableView.tableFooterView = [UIView new];
        [_myTableView setSeparatorInset:UIEdgeInsetsZero];
        adjustInset(_myTableView);
        [_myTableView registerClass:[ShippingAddressTableViewCell class] forCellReuseIdentifier:@"ShippingAddressTableViewCell"];
        UIView *tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWIDTH, KBottomSafeViewHeight)];
        tableFooterView.backgroundColor = [UIColor clearColor];
        self.myTableView.tableFooterView = tableFooterView;
        [self.view addSubview:_myTableView];
    }
    return _myTableView;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete){
        SelectAreaModel *model = [_mydateSource safeObjectAtIndex:indexPath.row];
        
        
        UIWindow  *alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        alertWindow.rootViewController = [[UIViewController alloc] init];
        alertWindow.windowLevel = UIWindowLevelAlert + 1;
        [alertWindow makeKeyAndVisible];
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"确定要删除收货地址?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"确定");
            NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
            param[@"id"] = model.id;
            [NetWorkTool POST:deleteAdd param:param success:^(id dic) {
                [self.mydateSource removeObjectAtIndex:indexPath.row];
                if (self.mydateSource.count>0) {
                    self.emptyImageView.hidden = YES;
                } else {
                    self.emptyImageView.hidden = NO;
                }
                [self.myTableView reloadData];
                
                ShowToastWithText(dic[@"msg"]);
                
            } other:^(id dic) {
                ShowToastWithText(dic[@"msg"]);
            } fail:^(NSError *error) {
                
            } needUser:YES];
        }];
        
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

//保存按钮 点击事件处理
- (void)footerButtonClick:(UIButton *)button {
    NSLog(@"您点击了 收货地址下面的 确定 按钮");
}

@end
